import tkinter as tk
from tkinter import messagebox, ttk, filedialog
import pandas as pd
from PIL import ImageGrab
from tkinter import Canvas
import ctypes
from ctypes import wintypes
import logging
import time
import re
import os
from number_generator import NumberGenerator
from number_generator_ui import NumberGeneratorUI
import subprocess 

# 常量定义
logging.basicConfig(filename='screenshot.log', level=logging.DEBUG)

# GUI界面类
class Application:
    def __init__(self):
        self.root = tk.Tk()
        self.hotkey_handles = []
        self.setup_ui()

    def setup_ui(self):
        """初始化界面"""
        self.root.title("测试工具集合")
        self.root.geometry("500x400")  # 调整窗口尺寸
        self.root.configure(bg='#f0f0f0')  # 设置背景色
        
        # 设置整体样式
        style = ttk.Style()
        style.theme_use('clam')  # 使用更现代的clam主题

        # 配置样式
        style.configure('TFrame', background='#f0f0f0', padding=10)
        style.configure('TButton',
                        background='#4a6ea9',
                        foreground='white',
                        font=('微软雅黑', 10),
                        padding=8,
                        borderwidth=0)
        style.map('TButton',
                  background=[('active', '#3a5a8f'), ('pressed', '#2a4a7f')])
        style.configure('TLabel',
                        background='#f0f0f0',
                        font=('微软雅黑', 10))
        style.configure('Title.TLabel',
                        font=('微软雅黑', 16, 'bold'),
                        foreground='#2a4a7f')

        # 主框架
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)

        # 标题标签
        title_frame = ttk.Frame(main_frame)
        title_frame.pack(fill=tk.X, pady=(0, 20))

        title_label = ttk.Label(title_frame,
                                text="测试工具集合",
                                style='Title.TLabel')
        title_label.pack()

        # 功能按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)

        # 证件号码生成按钮
        num_gen_btn = ttk.Button(btn_frame,
                                 text="证件号码生成器",
                                 command=self.open_number_generator)
        num_gen_btn.pack(fill=tk.X, pady=5)
        # 添加文件格式转换按钮
        file_conversion_btn = ttk.Button(btn_frame,
                                         text="文件格式转换(支持PDF转Word，PDF转Excel)",
                                         command=self.open_file_conversion)
        file_conversion_btn.pack(fill=tk.X, pady=5)
        # 测试证迹生成按钮
        test_trace_btn = ttk.Button(btn_frame,
                                    text="生成测试证迹",
                                    command=self.generate_test_traces)
        test_trace_btn.pack(fill=tk.X, pady=5)

        # 添加说明标签
        ttk.Label(btn_frame,
                  text='支持自定义字段导入到word文档中',
                  font=('微软雅黑', 8),
                  foreground="#666666").pack()
        # 截图工具区域
        screenshot_frame = ttk.Frame(main_frame)
        screenshot_frame.pack(fill=tk.X, pady=10)

        # 截图按钮
        screenshot_btn = ttk.Button(screenshot_frame,
                                    text="截图工具 (F1截图)",command=self.take_screenshot
                                    )
        screenshot_btn.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))

        # 添加 OCR 文字识别按钮
        ocr_btn = ttk.Button(btn_frame,
                             text="OCR 文字识别",
                             command=self.open_ocr)
        ocr_btn.pack(fill=tk.X, pady=5)

        # 底部信息
        info_frame = ttk.Frame(main_frame)
        info_frame.pack(fill=tk.X, pady=(20, 0))

        ttk.Label(info_frame,
                  text="©➷❤宇哥测试工具集合",
                  foreground="#999999",
                  font=('微软雅黑', 8)).pack(side=tk.RIGHT)

    def take_screenshot(self):
        """通过调用第三方软件实现截图功能"""
        try:
            import os
            # 获取当前脚本所在目录
            script_dir = os.path.dirname(os.path.abspath(__file__))
            # 构建 Snipaste.exe 的绝对路径
            snipaste_path = os.path.join(script_dir, "Snipaste2.10.5", "Snipaste.exe")
            subprocess.run([snipaste_path], check=True)
        except subprocess.CalledProcessError as e:
            messagebox.showerror("错误", f"调用第三方截图软件时出错: {str(e)}")
        except Exception as e:
            messagebox.showerror("错误", f"发生未知错误: {str(e)}")

    def generate_test_traces(self):
        """生成测试证迹文档"""
        try:
            # 选择Excel文件
            excel_path = filedialog.askopenfilename(
                title="选择测试案例Excel文件",
                filetypes=[("Excel文件", "*.xlsx"), ("所有文件", "*.*")]
            )
            if not excel_path:
                return

            # 读取Excel数据
            df = pd.read_excel(excel_path)

            # 检查是否有数据列
            if len(df.columns) == 0:
                messagebox.showerror("错误", "Excel中没有数据列")
                return

            # 创建字段选择窗口
            select_window = tk.Toplevel(self.root)
            select_window.title("选择导出字段")
            select_window.geometry("500x400")
            select_window.resizable(False, False)

            # 主框架
            main_frame = ttk.Frame(select_window, padding=10)
            main_frame.pack(fill=tk.BOTH, expand=True)

            # 标题
            title_frame = ttk.Frame(main_frame)
            title_frame.pack(fill=tk.X, pady=(0, 10))

            ttk.Label(title_frame,
                      text="请选择要导出的字段:",
                      font=('微软雅黑', 12)).pack(side=tk.LEFT)

            # 添加全选/全不选按钮
            btn_frame = ttk.Frame(title_frame)
            btn_frame.pack(side=tk.RIGHT)

            self.selected_fields = {}
            ttk.Button(btn_frame, text="全选",
                       command=lambda: [var.set(True) for var in self.selected_fields.values()]).pack(side=tk.LEFT,
                                                                                                      padx=5)
            ttk.Button(btn_frame, text="全不选",
                       command=lambda: [var.set(False) for var in self.selected_fields.values()]).pack(side=tk.LEFT)

            # 滚动区域
            canvas = tk.Canvas(main_frame, borderwidth=0, highlightthickness=0)
            scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=canvas.yview)
            scroll_frame = ttk.Frame(canvas)

            scroll_frame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
            canvas.create_window((0, 0), window=scroll_frame, anchor="nw")
            canvas.configure(yscrollcommand=scrollbar.set)

            # 使用网格布局
            canvas.pack(side="left", fill="both", expand=True)
            scrollbar.pack(side="right", fill="y")

            # 存储选择的字段
            self.selected_fields = {}

            # 添加复选框 - 每行3个
            for i, col in enumerate(df.columns):
                var = tk.BooleanVar(value=False)
                cb = ttk.Checkbutton(scroll_frame, text=col, variable=var)
                cb.grid(row=i // 3, column=i % 3, sticky="w", padx=5, pady=2)
                self.selected_fields[col] = var

            btn_frame = ttk.Frame(main_frame)
            btn_frame.pack(fill=tk.X, pady=(10, 0))

            def confirm_selection():
                selected_cols = [col for col, var in self.selected_fields.items() if var.get()]
                if not selected_cols:
                    messagebox.showerror("错误", "请至少选择一个字段")
                    return

                select_window.destroy()
                self._generate_documents(df, selected_cols)

            ttk.Button(btn_frame, text="确认", command=confirm_selection, width=15).pack(pady=5)

            # 让窗口居中显示
            select_window.update_idletasks()
            width = select_window.winfo_width()
            height = select_window.winfo_height()
            x = (select_window.winfo_screenwidth() // 2) - (width // 2)
            y = (select_window.winfo_screenheight() // 2) - (height // 2)
            select_window.geometry(f'+{x}+{y}')

        except Exception as e:
            messagebox.showerror("错误", f"生成测试证迹时出错: {str(e)}")

    def _generate_documents(self, df, selected_cols):
        """实际生成文档的方法"""
        try:
            # 选择保存路径
            save_dir = filedialog.askdirectory(title="选择测试证迹保存目录")
            if not save_dir:
                return

            # 为每个测试案例生成Word文档
            from docx import Document
            from docx.shared import Pt

            # 检查是否有案例编号列
            case_id_col = None
            possible_names = ['案例编号', '编号', 'ID', '测试案例编号', '测试编号', '用例编号', 'CaseID']
            for col in df.columns:
                # 模糊匹配：检查列名是否包含任何可能的名称
                if any(name in col for name in possible_names) and pd.notna(df[col]).any():
                    case_id_col = col
                    break

            for idx, row in df.iterrows():
                doc = Document()

                # 设置文档样式
                style = doc.styles['Normal']
                font = style.font
                font.name = '微软雅黑'
                font.size = Pt(10.5)

                # 添加内容
                for col in selected_cols:
                    if col in row and pd.notna(row[col]):
                        doc.add_heading(col, level=2)
                        doc.add_paragraph(str(row[col]))

                # 保存文档(优先使用案例编号作为文件名)
                if case_id_col and pd.notna(row[case_id_col]):
                    # 清理文件名并去除前后空格
                    safe_name = str(row[case_id_col]).strip()
                    # 替换所有非法字符为下划线
                    safe_name = re.sub(r'[\\/:*?"<>|]', '_', safe_name)
                    # 确保文件名长度合理
                    safe_name = safe_name[:50]  # 限制最大长度
                    doc_path = f"{save_dir}/{safe_name}.docx"
                    # 检查文件是否已存在
                    if os.path.exists(doc_path):
                        messagebox.showwarning("文件已存在", f"已存在同名的文件:\n{doc_path}")
                        return
                else:
                    doc_path = f"{save_dir}/案例_{idx + 1}.docx"
                doc.save(doc_path)

            messagebox.showinfo("完成", f"已成功生成 {len(df)} 个测试证迹文档")

        except Exception as e:
            messagebox.showerror("错误", f"生成文档时出错: {str(e)}")

    def open_ocr(self):
        """OCR 文字识别功能占位方法，后续实现具体功能"""
        pass



    def open_file_conversion(self):
        """打开文件转换页面"""
        self.root.destroy()
        from file_conversion_ui import FileConversionUI
        FileConversionUI().run()

    def open_number_generator(self):
        """打开号码生成界面"""
        self.root.destroy()
        NumberGeneratorUI().run()

    def run(self):
        """运行主程序"""
        self.root.mainloop()
